<template>
  <div id="upsert">
    <el-card class="box-card">
      <h3>商品（Spu）介绍</h3>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="160px"
        class="demo-ruleForm"
      >
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="原始价格" prop="originalPrice">
          <el-input v-model="ruleForm.originalPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="price">
          <el-input v-model="ruleForm.price" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPrice">
          <el-input v-model="ruleForm.vipPrice" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="stock">
          <el-input v-model="ruleForm.stock" disabled></el-input>
        </el-form-item>
        <el-form-item label="运费模板" prop="freightTemplateId">
          <el-select v-model="ruleForm.freightTemplateId" placeholder="请选择商品运费模板">
            <el-option
              v-for="item in freightoptions"
              :key="item.freightTemplateDO.id"
              :label="item.freightTemplateDO.templateName"
              :value="item.freightTemplateDO.id"
            >
              <template></template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在售" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="0">在售</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            action="http://192.168.1.99:8080/upload/admin"
            list-type="picture-card"
            :on-success="handleAvatar"
            v-model="ruleForm.imgList"
            :file-list="imgs"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit">
          <el-input v-model="ruleForm.unit" placeholder="件/个/盒"></el-input>
        </el-form-item>
        <el-form-item label="所属类目" prop="categoryId">
          <el-cascader
            v-model="ruleForm.categoryId"
            :options="options"
            :props="{ expandTrigger: 'hover',checkStrictly: true }">
          </el-cascader>
        </el-form-item>
        <el-form-item label="商品简介" prop="description">
          <el-input v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="商品详细介绍" prop="detail">
            <editor v-model="ruleForm.detail" :init="init"></editor>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <h3>商品类型(sku)</h3>
      <el-button type="primary" plain @click="addsku(0)">添加</el-button>
      <el-table
        :data="ruleForm.skuList"
        style="width: 100%">
        <el-table-column
          prop="barCode"
          label="Sku条形码">
        </el-table-column>
        <el-table-column
          prop="title"
          label="类型名">
        </el-table-column>
        <el-table-column
          prop="originalPriceRaw"
          label="原价">
        </el-table-column>
        <el-table-column
          prop="priceRaw"
          label="现价">
        </el-table-column>
        <el-table-column
          prop="vipPriceRaw"
          label="vip价">
        </el-table-column>
        <el-table-column
          prop="stock"
          label="库存">
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="handleDelete(scope.$index,0)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card">
      <h3>商品参数</h3>
      <el-button type="primary" plain @click="addsku(1)">添加</el-button>
       <el-table
        :data="ruleForm.attributeList"
        style="width: 100%">
       <el-table-column
          prop="attribute"
          label="商品参数名称">
        </el-table-column><el-table-column
          prop="value"
          label="商品参数值">
        </el-table-column>
        <el-table-column
          prop="address"
          label="操作">
          <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="handleDelete(scope.$index,1)"
          >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      title="添加商品类型（Sku）"
      :visible.sync="dialogVisible">
      <el-form :model="ruleFormSku" status-icon :rules="ruleSkes" ref="ruleFormSku" label-width="100px" class="demo-ruleFormSku" style="width:400px;margin-left: 50px">
        <el-form-item label="Sku条形码" prop="barCode">
          <el-input v-model="ruleFormSku.barCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类型名称" prop="title">
          <el-input v-model="ruleFormSku.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片(可空)">
          <el-upload
            class="avatar-uploader"
            action="http://192.168.1.99:8080/upload/admin"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="ruleFormSku.img" :src="ruleFormSku.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="原始价格" prop="originalPriceRaw">
          <el-input v-model="ruleFormSku.originalPriceRaw" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="priceRaw">
          <el-input v-model="ruleFormSku.priceRaw" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPriceRaw">
          <el-input v-model="ruleFormSku.vipPriceRaw" placeholder="0.00">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="ruleFormSku.stock" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitFormSku('ruleFormSku')">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="设置商品参数"
      :visible.sync="parameterDialogVisible">
      <el-form :model="ruleFormParameter" status-icon :rules="rulesParameter" ref="ruleFormParameter" label-width="120px" class="demo-ruleFormSku" style="width:400px;margin-left: 50px">
        <el-form-item label="商品参数名称" prop="attribute">
          <el-input v-model="ruleFormParameter.attribute" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品参数值" prop="value">
          <el-input v-model="ruleFormParameter.value" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="parameterDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFormcs('ruleFormParameter')">确 定</el-button>
      </span>
    </el-dialog>
    <div style="padding-bottom: 20px;">
      <router-link to='/goods/goodslist'>
         <el-button>取 消</el-button>
      </router-link>
      <el-button type="primary" @click="submitForm('ruleForm')" style="margin-left: 10px;">{{name}}</el-button>
    </div>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce'
  import 'tinymce/themes/silver'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/code'
  import 'tinymce/icons/default'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/skins/ui/oxide/skin.css'

import goodslist from "@/api/goodslist";
export default {
  data() {
    var validateTitle = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("商品名称不能为空"));
      } else {
        callback();
      }
    };
    var validateOriginalPriceRaw = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("商品原价不能为空"));
      } else {
       let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validatePriceRaw = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("商品现价不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateVipPriceRaw = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("商品Vip价格不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateStatus = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请选择商品状态"));
      } else {
        callback();
      }
    };
    var validateUnit = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("物件单位不能为空"));
      } else {
        callback();
      }
    };
    var validateDetail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("商品详细介绍不能为空"));
      } else {
        callback();
      }
    };
    var validateBarCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型条码不能为空"));
      } else {
        callback();
      }
    };
    var validateTitles = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型名称不能为空"));
      } else {
        callback();
      }
    };
    var validateOriginalPriceRaws = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型原价不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validatePriceRaws = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型现价不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateVipPriceRaws = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型Vip价格不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateStocks = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("类型库存不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    var validateAttribute = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("属性名称不能为空"));
      } else {
        callback();
      }
    };
    var validateValue = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("属性值不能为空"));
      } else {
        let reg = /^[1-9][0-9]{0,}$/;
        if (reg.test(value)) {
            callback();
        } else {
          callback(new Error("请输入大于零的数整"));
        }
      }
    };
    return {
      name:"",//按钮名字
      ruleForm: {
        //表单数据
        title:"",//商品名称
        originalPriceRaw:"",//原始价格
        priceRaw:0,//当前价格
        vipPriceRaw:"",//VIP价格
        stock:0,//剩余库存
        status:"",//是否在售
        imgList:[],//商品图片数组
        unit:"",//商品单位
        categoryId:"",//所属类目
        description:"",//商品简介
        detail:"",//商品详细介绍
        skuList:[],//商品类型
        attributeList:[],//商品参数
        img:"",//图片
        freightTemplateId:null,//运费模板
        price:0,//当前价格
        originalPrice:0,//原始价格
        vipPrice:0,//VIP价格

      },
      rules: {
        //表单验证
        title: [{ required: true, validator: validateTitle, trigger: "blur" }],
        originalPrice: [{ required: true, validator: validateOriginalPriceRaw, trigger: "blur" }],
        price: [{ required: true, validator: validatePriceRaw, trigger: "blur" }],
        vipPrice: [{ required: true, validator: validateVipPriceRaw, trigger: "blur" }],
        status: [{ required: true, validator: validateStatus, trigger: "change" }],
        unit: [{ required: true, validator: validateUnit, trigger: "blur" }],
        detail: [{ required: true, validator: validateDetail, trigger: "blur" }],

      },
      imgs:[],//图片数组
      dialogVisible: false,//Sku对话框可视
      parameterDialogVisible:false,//参数对话框可视
      options:[],//SPU树选项数据
      freightoptions:[],//运费模板
      tableData:[],//列表数据
      ruleFormSku:{//表单数据sku
        barCode: "",//Sku条形码
        title:"",//类型名
        originalPriceRaw: "",//原价
        priceRaw: "",//现价
        vipPriceRaw: "",//vip价
        img:"",//图片
        stock:"",//库存
        price:0,//现价
        originalPrice:0,//原价
        vipPrice:0,//vip价
      },
      ruleSkes:{//表单数据sku验证
        barCode: [{ required: true, validator: validateBarCode, trigger: "blur" }],
        title: [{ required: true, validator: validateTitles, trigger: "blur" }],
        originalPriceRaw: [{ required: true, validator: validateOriginalPriceRaws, trigger: "blur" }],
        priceRaw: [{ required: true, validator: validatePriceRaws, trigger: "blur" }],
        vipPriceRaw: [{ required: true, validator: validateVipPriceRaws, trigger: "blur" }],
        stock: [{ required: true, validator: validateStocks, trigger: "blur" }],
      },
      ruleFormParameter:{//表单数据参数
        attribute:"",
        value:""
      },
      rulesParameter:{//表单数据参数验证
        attribute: [{ required: true, validator: validateAttribute, trigger: "blur" }],
        value: [{ required: true, validator: validateValue, trigger: "blur" }],
      },
        init: {//富文本框
          language_url: '/langs/zh_CN.js',
          language: 'zh_CN',
          height: 300,
          plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',
          toolbar: 'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat',
          branding: true,
          menubar: true,
          images_upload_handler: (blobInfo, success) => {
            const img = 'data:image/jpeg;base64,' + blobInfo.base64()
            success(img)
          }
        },
    };
  },
    mounted() {
      tinymce.init({})
    },
    components: {
      Editor
    },
  created: function() {
    if (this.$route.query.id==undefined) {
      this.name="保存商品"
    }else{
      this.name="修改商品"
      goodslist.details({ spuId: this.$route.query.id }).then((res) => {//详细
          console.log(res);
          if (res.data.errmsg == "成功") {
            this.ruleForm = res.data.data;
            this.ruleForm.categoryId="C_"+this.ruleForm.categoryId
            this.ruleForm.originalPrice =this.ruleForm.originalPrice/100
            this.ruleForm.price =this.ruleForm.price/100
            this.ruleForm.vipPrice =this.ruleForm.vipPrice/100
            for (const i in this.ruleForm.skuList) {
            this.ruleForm.skuList[i].originalPriceRaw =this.ruleForm.skuList[i].originalPrice/100
            this.ruleForm.skuList[i].priceRaw =this.ruleForm.skuList[i].price/100
            this.ruleForm.skuList[i].vipPriceRaw =this.ruleForm.skuList[i].vipPrice/100
            }
            this.imgurl()
          }else{
            this.topTips(res.data.errmsg, "error");
          }
      });
    }
    console.log(this.$route.query.id,this.name)
    goodslist.freightInquire().then((res) => {//运费模板
      console.log(res);
      this.freightoptions = res.data.data
    })
    goodslist.getSpuBigTree().then((res) => {//SPU树选项
      console.log(res);
      this.options = this.getTreeData(res.data.data);
    })
  },
  methods: {
    addsku(index){//商品的添加
    let _this=this
      if (index==0) {
        this.dialogVisible = true
        setTimeout(function(){
          _this.resetForm('ruleFormSku')
        },500)
        
      }else{
        this.parameterDialogVisible = true
        setTimeout(function(){
          _this.resetForm('ruleFormParameter')
         },500)
      }
    },
    submitFormSku(formName) {//添加表单sku
      let that =this
        this.$refs[formName].validate((valid) => {
          if (valid) {
             if (parseFloat(that.ruleFormSku.originalPriceRaw)>=parseFloat(that.ruleFormSku.priceRaw)&&parseFloat(that.ruleFormSku.priceRaw)>=parseFloat(that.ruleFormSku.vipPriceRaw)) {
                that.ruleFormSku.price=that.ruleFormSku.priceRaw*100
                that.ruleFormSku.originalPrice=that.ruleFormSku.originalPriceRaw*100
                that.ruleFormSku.vipPrice=that.ruleFormSku.vipPriceRaw*100
                let data =JSON.parse(JSON.stringify(that.ruleFormSku)); 
                this.dialogVisible = false
                this.ruleForm.skuList.push(data)
                console.log(this.ruleForm.skuList)
            }else{
              that.topTips("原价>=现价>=VIP价格", "error");
            }
          } else {
            return false;
          }
        });
    },
    submitFormcs(formName) {//添加类型表单
      let that =this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data =JSON.parse(JSON.stringify(that.ruleFormParameter)); 
            this.parameterDialogVisible = false
            this.ruleForm.attributeList.push(data)
            
          } else {
            return false;
          }
        });
    },
    resetForm(formName) {//重置
        this.$refs[formName].resetFields();
    },
    handleDelete(index,data){//删除
      if (data==0) {
        this.ruleForm.skuList.splice(index, 1);
      }else{
        this.ruleForm.attributeList.splice(index, 1);
      }
    },
    imgurl(){
      //循环遍历图片数组
      this.ruleForm.imgList.forEach((item, i) => {
        //添加ulr
        return this.imgs.push({
          name: i + 1,
          url: item,
        });
      });
    },
    submitForm(formName) {//添加表单
      let that =this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log(666)
            console.log(that.ruleForm)
            if (parseFloat(that.ruleForm.originalPrice)>=parseFloat(that.ruleForm.price)&&parseFloat(that.ruleForm.price)>=parseFloat(that.ruleForm.vipPrice)) {
              if (that.ruleForm.freightTemplateId!=null) {
                if (that.ruleForm.imgList.length!=0) {
                  if (that.ruleForm.categoryId!="") {
                      that.ruleForm.img = that.ruleForm.imgList[0]
                      that.ruleForm.price=that.ruleForm.price*100
                      that.ruleForm.originalPrice=that.ruleForm.originalPrice*100
                      that.ruleForm.vipPrice=that.ruleForm.vipPrice*100
                      if (typeof(that.ruleForm.categoryId)=="object") {
                        that.ruleForm.categoryId=that.ruleForm.categoryId[that.ruleForm.categoryId.length-1]
                        that.ruleForm.categoryId=that.ruleForm.categoryId.substr(2,)
                      }else{
                        that.ruleForm.categoryId=that.ruleForm.categoryId.substr(2,)
                      }
                      if (that.name=="修改商品") {
                        goodslist.edit({
                          spuDTO:JSON.stringify(that.ruleForm)
                        }).then(res =>{
                            console.log(res)
                            if (res.data.errmsg == "成功") {
                                that.topTips(res.data.errmsg, "success");
                                that.$router.push('/goods/goodslist');
                            }else{
                                that.topTips(res.data.errmsg, "error");
                            }
                        })
                      }else{
                        goodslist.create({
                          spuDTO:JSON.stringify(that.ruleForm)
                        }).then(res =>{
                            console.log(res)
                            if (res.data.errmsg == "成功") {
                                that.topTips(res.data.errmsg, "success");
                                that.$router.push('/goods/goodslist');
                            }else{
                                that.topTips(res.data.errmsg, "error");
                            }
                        })
                      }
                  } else {
                    that.topTips("所属类目不可以为空", "error");
                  }
                } else {
                  that.topTips("请上传至少一张图片", "error");
                }
              } else {
                that.topTips("运费模板不可以为空", "error");
              }
            }else{
              that.topTips("原价>=现价>=VIP价格", "error");
            }
          } else {
            that.topTips("表格不完善", "error");
            return false;
          }
        });
    },
    handleAvatar(res) {
      this.ruleForm.imgList.push(res.url);
    },
    handleAvatarSuccess(res) {
        this.ruleFormSku.img = res.url;
      },
    beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    getTreeData(data) {
      //递归方法
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          //children是数据库中的变量名
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children); //返回元素的子元素的集合有数据继续导出
        }
      }
      return data;
    },
    
  }
};
</script>

<style lang="less" scoped>
#upsert {
  //内容填满
  height: 100%;
  padding: 20px;
}
h3 {
  padding: 15px 0px 10px 0px;
}
.box-card{
  margin-bottom: 10px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-cascader-panel  div {
  width: 200px;
}
.el-table {
  font-size: 13px;
}
.el-main {
  line-height: 0px !important;
}
</style>
